package com.zhanglu.fun.services.website.login;

import com.zhanglu.fun.services.website.bean.response.UserResponse;
import com.zhanglu.fun.services.website.client.AuthenticationClient;
import com.zhanglu.fun.services.website.common.ResultResponse;
import com.zhanglu.fun.tookit.json.JsonTools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @description
 * @Auther zhanglu
 * @Date 2017/9/20 下午3:58
 */
@Service
@Slf4j
public class LoginService {
    @Autowired
    private AuthenticationClient authenticationClient;

    public ResultResponse login(HttpServletResponse httpServletResponse, String account, String password) {
        UserResponse user = authenticationClient.login(account, password);
        log.debug("{}", JsonTools.toJSONString(user));
        if (!Objects.isNull(user)) {
            setCookie(httpServletResponse, user.getToken());
        }
        return new ResultResponse<>(!Objects.isNull(user), user);
    }

    public void setCookie(HttpServletResponse httpServletResponse, String token) {
        Cookie cookie = new Cookie("user_token", token);
        cookie.setMaxAge(60 * 60 * 12 * 14);
        cookie.setPath("/");
        httpServletResponse.addCookie(cookie);
    }
}
